package org.hxzon.cyclone;

import java.lang.reflect.ParameterizedType;

//对象复用，但对象复用前并未清理
public class Array<T> {

    private Object[] array;
    private int curIndex;
    private Class<T> clazz;

    @SuppressWarnings("unchecked")
    public Array(int capacity) {
        array = new Object[capacity];
        clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public T get() {
        if (curIndex == array.length) {
            return null;
        }
        if (array[curIndex] == null) {
            try {
                array[curIndex] = clazz.newInstance();//不支持接口和抽象类，父类
            } catch (InstantiationException e) {
            } catch (IllegalAccessException e) {
            }
        }
        return (T) array[curIndex++];
    }

    public void clear() {
        curIndex = 0;
    }

    public boolean isFull() {
        return curIndex == array.length;
    }

    public int capacity() {
        return array.length;
    }

    public int size() {
        return curIndex;
    }
}
